<template>
  <div>
    <el-row :gutter="10" style="padding: 10px">
      <el-col :xs="0" :lg="3"></el-col>
      <el-col :xs="24" :lg="5">
        <el-card style="height: 605px">
          <template #header>
            <div class="title_top">
              <span>热搜食谱</span>
            </div>
          </template>
          <el-carousel
            :interval="1500"
            arrow="always"
            style="border-radius: 10px"
            height="500px"
            width="300px"
            
          >
            <el-carousel-item
              v-for="item in meals"
              :key="item"
              style="width: 100%;display: flex;justify-content: center;"
              label=""
            >
            <el-image style="width: 100%; height: 100%" :src="item.image" fit="fill" />
              <!-- <img style="height: 100%; width: 100%" :src="item.image" /> -->
            </el-carousel-item>
          </el-carousel>
        </el-card>
      </el-col>
      <el-col :xs="24" :lg="13">
        <div class="card_container">
          <el-card class="calender-container">
            <el-calendar  :range="[currentWeekStartDate,currentWeekEndDate]" style=" width: 100%;" v-model="selectedDates
            ">
              <template #header="{ date }">
                <span>本周打卡情况</span>
                <span>{{ date }}</span>
                </template>
              <template #date-cell="{ data }" >
                
                  <p @click="handleClick(data)">
                    {{ data.day.split('-').slice(1).join('-') }}
                    <span v-if="isDatePunched(data.day)">&#128540</span>
                  </p>
                  <span v-if="isToday(data.day)">今日</span>
            </template>

          </el-calendar>
          </el-card>
          <!--三餐-->
          <el-card class="box-card">
            <template #header>
              <div class="today_menu">
                <span>今日三餐</span>
                <div>
                  <el-button
                    :type="currentType == 0 ? 'primary' : ''"
                    @click="changeMealType(0)"
                    round
                    >早餐</el-button
                  >
                  <el-button
                    :type="currentType == 1 ? 'primary' : ''"
                    @click="changeMealType(1)"
                    round
                    >午餐</el-button
                  >
                  <el-button
                    :type="currentType == 2 ? 'primary' : ''"
                    @click="changeMealType(2)"
                    round
                    >晚餐</el-button
                  >
                </div>
              </div>
            </template>

            <el-carousel
              :autoplay="false"
              ref="carousel"
              arrow="never"
              :loop="false"
              :initial-index="getType()"
              indicator-position="none"
            >
            <el-empty v-if="mergedObject.length == 0" description="description" />
              <el-carousel-item v-else
                v-for="(chunk, index) in mergedObject"
                :key="index"
                loop="false"
              >
              
                <el-row>
                  <el-col
                    v-for="(item, index) in chunk"
                    :key="item.id"
                    :xs="8"
                    :sm="6"
                    :md="6"
                    :lg="6"
                  >
                    <el-card
                      :body-style="{ padding: '10px' }"
                      style="height: 300px; width: 200px"
                    >
                      <img
                        :src="item.image"
                        class="image"
                        style="width: 180px; height: 200px"
                      />
                      <div style="padding: 14px">
                        <span>{{ item.Dish_name }}</span>
                        <div class="bottom">
                          <el-text truncated
                            >功效：{{ item.category.slice(1, -1) }}</el-text
                          >
                          <el-button
                            text
                            class="button"
                            type="primary"
                            @click="toDetail(item.id)"
                            >详情</el-button
                          >
                        </div>
                      </div>
                    </el-card>
                  </el-col>
                </el-row>
              </el-carousel-item>
            </el-carousel>
          </el-card>
          
        </div>
      </el-col>
      <el-col :xs="0" :lg="3"></el-col>
    </el-row>
    <el-row :gutter="10" style="padding: 10px">
      <el-col :xs="0" :lg="3"></el-col>
      <el-col :xs="24" :lg="9">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>最新食谱</span>
            </div>
          </template>
          <el-row>
            <el-col
              v-for="(item, index) in newMeals"
              :key="item.id"
              :xs="12"
              :sm="8"
              :md="6"
              :lg="8"
              :offset="0"
              ><el-badge value="new" class="item">
                <el-card
                  :body-style="{ padding: '10px' }"
                  style="height: 300px; width: 200px"
                >
                  <img
                    :src="item.image"
                    class="image"
                    style="width: 180px; height: 200px"
                  />
                  <div style="padding: 14px">
                    <span>{{ item.Dish_name }}</span>
                    <div class="bottom">
                      <el-text truncated
                        >功效：{{ item.category.slice(1, -1) }}</el-text
                      >
                      <el-button
                        text
                        class="button"
                        type="primary"
                        @click="toDetail(item.id)"
                        >详情</el-button
                      >
                    </div>
                  </div>
                </el-card></el-badge
              >
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      <el-col :xs="24" :lg="9">
        <el-card
          ><template #header>
            <div class="card-header">
              <span>最多收藏</span>
            </div>
          </template>
          <el-row>
            <el-col
              v-for="(item, index) in favMeals"
              :key="item.id"
              :xs="12"
              :sm="8"
              :md="6"
              :lg="8"
              :offset="0"
            >
              <el-badge :value="item.fav_num" :max="99" class="item">
                <el-card
                  :body-style="{ padding: '10px' }"
                  style="height: 300px; width: 200px"
                >
                  <img
                    :src="item.image"
                    class="image"
                    style="width: 180px; height: 200px"
                  />
                  <div style="padding: 8px">
                    <span
                      style="
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                      "
                      >{{ item.Dish_name }}</span
                    >
                    <div class="bottom">
                      <el-text truncated
                        >功效：{{ item.category.slice(1, -1) }}</el-text
                      >
                      <el-button
                        text
                        class="button"
                        type="primary"
                        @click="toDetail(item.id)"
                        >详情</el-button
                      >
                    </div>
                  </div>
                </el-card></el-badge
              >
            </el-col>
          </el-row></el-card
        >
      </el-col>
      <el-col :xs="0" :lg="3"></el-col>
    </el-row>
  </div>
  <el-dialog v-model="isRecord" :title="title" width="40%" center>
    <el-form :inline="true" style="margin-left: 30%">
      <el-form-item label="体重(kg)">
        <el-input-number
          :precision="2"
          :step="0.1"
          size="middle"
          v-model="newWeight.weight"
        ></el-input-number>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="handleEditWeightRecord()">
          上传
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from "vue";
import {
  reqGetMeal,
  reqGetThree,
  reqNewMeals,
  reqTopFav,
  reqHotList,
  reqHostMeals,
  reqRecommendMeals
} from "@/api/menu";
import {reqRecordWeight,reqUserInfo} from '@/api/user';
import moment from 'moment'; 
import { useRouter } from "vue-router";
import { getType } from "@/utils/time";
import useUserStore from "@/store/modules/user";
import {ElMessage} from 'element-plus';
let userStore = useUserStore();
let router = useRouter();
const meals = ref([]);
const selectedDate =ref(new Date());
const threeMeals = ref([]);
const currentType = ref("");
const mergedObject = ref({});
const newMeals = ref([]);
const favMeals = ref([]);
let carousel = ref();
const hotList = ref([]);
const Records = ref([]);//打卡记录
const isRecord = ref(false);
const title = ref("");
const newWeight = ref({
  date: "",
  weight: 0.0,
  user_id: "",
});
const currentWeekStartDate = ref();
const currentWeekEndDate = ref();
const setCurrentWeekRang=() => {
const today = new Date();
  const firstDayOfWeek = new Date(today.setDate(today.getDate() - today.getDay()));
  const lastDayOfWeek = new Date(today.setDate(today.getDate() - today.getDay() + 6));
  currentWeekStartDate.value = firstDayOfWeek;
  currentWeekEndDate.value = lastDayOfWeek;
}
const isToday =(date)=> {
      const today = new Date().toISOString().split('T')[0];
      return date === today;
}
const handleClick = (data) =>{
  isRecord.value = true;
  newWeight.value.date = moment(data.day).format('YYYY-MM-DD');
  title.value = newWeight.value.date + '打卡';
  console.log(data.day)
}
const handleEditWeightRecord = async () => {
  newWeight.value.user_id = parseInt(userStore.id)
  let res = await reqRecordWeight(newWeight.value)
  if(res.code == 200){
    ElMessage.success("上传成功")
    isRecord.value = false
  }else{
    ElMessage.error("上传失败")
  }
  isRecord.value = false;
  getUserWeight();
};
const cancel =()=>{
  isRecord.value = false;
}
const getUserWeight = async () => {
  let res = await reqUserInfo(userStore.id)
  // Records.value = res.data
  console.log(res.data.weight_change)
  Records.value = res.data.weight_change
};
const isDatePunched = (date)=> { 
  let res = false
  Records.value.forEach(item => {
  const keys = Object.keys(item);
  console.log(keys[0],"---------",date)
  if(keys[0] === date)  res=true
});
//(record => record.date === date); //{ date: '2024-03-25' },
  return res
}
onMounted(async () => {
  getMeals();
  getNewMeals();
  getHotList();
  await getUserWeight();
  setCurrentWeekRang();
  await getThreeType();
  initType();
});

const getHotList = async () => {
  let res = await reqHotList();
  hotList.value = res.data;
};
//轮播素材
const getMeals = async () => {
  let res = await reqHostMeals();

  meals.value = res.data;
  console.log(res);
};
//获取最新食谱和收藏
const getNewMeals = async () => {
  let res = await reqNewMeals();
  newMeals.value = res.data;
  let res1 = await reqTopFav();
  favMeals.value = res1.data;
};
//初始化当前时间段
const initType = () => {
  currentType.value = getType();
  carousel.value.setActiveItem(getType());
};
const changeMealType = (type) => {
  currentType.value = type;
  carousel.value.setActiveItem(type);
};
//三餐素材
const getThreeType = async () => {
  let res = await reqRecommendMeals(userStore.id);
  threeMeals.value = res.data;
  var chunk1 = threeMeals.value.slice(0, 4);
  var chunk2 = threeMeals.value.slice(4, 2 * 4);
  var chunk3 = threeMeals.value.slice(2 * 4);
  mergedObject.value = {
    breakfast: chunk1,
    lunch: chunk2,
    dinner: chunk3,
  };
  console.log(mergedObject);
};
//详情跳转
const toDetail = (id) => {
  router.push({
    path: "/detail",
    query: {
      id,
    },
  });
  console.log(id);
};
</script>

<style lang="scss" scoped>
.hotsearch {
  display: flex;
  flex-direction: row;
}
.title_top {
  display: flex;
  justify-content: space-between;
}
.card_container {
  height: 550px;
}
.today_menu {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 15px;
}
.bottom {
  margin-top: 13px;
  line-height: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.button {
  padding: 0;
  min-height: auto;
}

.image {
  width: 100%;
  display: block;
  border-radius: 10px;
}
.calender-container {
    width: 100%; /* 或者您想要的具体宽度 */
    height: 200px;
    font-size: smaller;
    margin-bottom: 10px;
  }
</style>
